<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace suifeng\mvc\admin;

use suifeng\builder\FormBuilder;

abstract class ModuleController extends AdminController
{
    /**
     * 模块名称。
     */
    protected $module_name;

    public function index()
    {
        $module_file_info = service('admin/module')->invoke_module_method($this->module_name, 'module_info');
        if (empty($module_file_info['config'])) {
            $this->error('此模块没有配置参数', url(config('ADMIN_INDEX_URL')));
        }

        $module_db_info = model('admin/module')->getByName($this->module_name);

        $form_builder = new FormBuilder();
        $form_builder->array_name = 'config';
        foreach ($module_file_info['config'] as $key => $config) {
            $form_builder->add_control($key, isset($config['control']) ? $config['control'] : 'text', null, $config);
        }

        if (request()->isPost()) {
            if ($form_builder->is_valid()) {
                $result = model('admin/module')
                    ->where(['id' => $module_db_info['id']])
                    ->update(['config' => json_encode($form_builder->acceptted_data)]);

                if ($result) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        } else {
            $config_array = array();

            // 获取模块文件的中配置
            foreach ($module_file_info['config'] as $key => $config) {
                $config_array[$key] = isset($config['value']) ? $config['value'] : null;
            }

            // 合并数据库中的模块配置
            if ($module_db_info['config']) {
                $module_db_info['config'] = json_decode($module_db_info['config']);

                foreach ($module_db_info['config'] as $key => $value) {
                    if (array_key_exists($key, $config_array)) {
                        $config_array[$key] = $value;
                    }
                }
            }

            $form_builder->initialize($config_array);
        }

        $tpl_name = 'admin@public/model_form';
        $tpl_vars['content'] = $form_builder->render_html();
        $tpl_vars['title'] = '表单';
        $this->display($tpl_name, $tpl_vars);
    }
}
